/****************************************************
 * Description: Controllar for 菜单
 * Copyright:   Copyright (c) 2013
 * Company:     beiwaionline
 * @author      bfsu
 * @version     1.0
 * @see
	HISTORY
	*  2013-08-08 bfsu Create File
	*  2013-08-14 fujin 创建查看，删除菜单
**************************************************/

package com.bfsuol.bfsuolframework.security.controller;


import com.baomidou.mybatisplus.extension.service.IService;
import com.bfsuol.bfsuolframework.core.BfsuolConstants;
import com.bfsuol.bfsuolframework.core.controller.CRUDControllerSupportV2;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.exception.ValidationException;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import com.bfsuol.bfsuolframework.security.PrivilegeService;
import com.bfsuol.bfsuolframework.security.annotations.*;
import com.bfsuol.bfsuolframework.security.dao.Menu;
import com.bfsuol.bfsuolframework.security.entity.dto.MenuDTO;
import com.bfsuol.bfsuolframework.security.entity.dto.Privilege;
import com.bfsuol.bfsuolframework.security.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/components/security/menu")
@Api(tags = {"菜单操作"})
public class MenuController extends SpringControllerSupport {

    @Autowired
    private MenuService menuService;

	@SecPrivilege(title="菜单管理")
	@RequestMapping("/index")
	@ApiOperation(value = "菜单首页",httpMethod = "GET")
	public ModelAndView index(Model model){

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("index"));
		return modelAndView;
	}

	@SecList
	@ApiOperation(value = "菜单列表",httpMethod = "GET")
	@RequestMapping("/list")
	public ModelAndView list(
			@QueryParameter("query") QueryParam query,
			@ModelAttribute("page") Pagination page,Model model){
		List<MenuDTO> menus = menuService.getCategoryMenus();
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("list"));
		model.addAttribute("menus", menus);
		return modelAndView;
	}

	@SecCreate
	@RequestMapping("/input")
	public ModelAndView create(@ModelAttribute Menu menu,Model model){
		model.addAttribute("privileges", PrivilegeService.getPrivileges());
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("input"));
		return modelAndView;
	}




	@SecEdit
	@RequestMapping("/input/{id}")
	public String edit(@PathVariable("id") Long id, Model model){
		Menu menu = menuService.getById(id);
		model.addAttribute("privileges", PrivilegeService.getPrivileges());
		model.addAttribute(menu);
		if(menu.getParentId()!=null){
			Menu parentMenu=menuService.getById(menu.getParentId());
			model.addAttribute("parent", parentMenu);
		}
		return getViewNamedPath("input");
	}
	/**
	 * 在当前菜单下添加子菜单
	 * @param id 当前菜单的id
	 * @param model
	 * @return
	 */
	@SecCreate
	@RequestMapping("/addChild/{id}")
	public String addChildMenu(@PathVariable("id") Long id, Model model){
		Menu menu = new Menu();
		model.addAttribute("addChild",true);
		model.addAttribute("privileges", PrivilegeService.getPrivileges());
		menu.setParentId(id);
		model.addAttribute(menu);
		if(menu.getParentId()!=null){
			Menu parentMenu=menuService.getById(menu.getParentId());
			model.addAttribute("parent", parentMenu);
		}
		return getViewNamedPath("input");
	}

	@SecCreate
	@SecEdit
	@RequestMapping("/save")
	public @ResponseBody MessageJson save(@ModelAttribute Menu menu){
		StringBuffer message = new StringBuffer();
		if(!this.validate(menu, message))//数据校验
			throw new ValidationException(message.toString());
		if(menu.isNew()){
			menu.setIsEnabled(BfsuolConstants.GLOBAL_YESNO_YES);
			menu.setIsSys(BfsuolConstants.GLOBAL_YESNO_YES);
			if(null != menu.getPrivilegeCode() || !menu.getPrivilegeCode().equals("")){
				menu.setUrl(this.getPrivilegeURL(menu.getPrivilegeCode()));
			}
			menuService.save(menu);
		}else{
			Menu temp = menuService.getById(menu.getId());
			temp.setOrderSn(menu.getOrderSn());
			temp.setDescription(menu.getDescription());
			temp.setTitle(menu.getTitle());
			temp.setParentId(menu.getParentId());
			temp.setPrivilegeCode(menu.getPrivilegeCode());
			temp.setUrl(this.getPrivilegeURL(menu.getPrivilegeCode()));
			temp.setId(menu.getId());
			menuService.updateById(temp);
		}
		return MessageJson.information("保存成功");
	}

	@SecDelete
	@RequestMapping("/delete/{id}")
	public @ResponseBody MessageJson delete(@PathVariable("id") Long id){
		if(menuService.deleteMenu(id))
			return MessageJson.information("成功删除");
		else
			throw new ValidationException("删除失败");
	}
	/**
	 * 删除指定的菜单
	 * @param id 菜单id
	 * @return
	 */
	@SecDelete
	@RequestMapping("/deleteMenu/{id}")
	public @ResponseBody MessageJson deleteMenu(@PathVariable("id") Long id){
		if(menuService.deleteMenu(id))
			return MessageJson.information("成功删除");
		else
			throw new ValidationException("删除失败");
	}
	@SecDelete
	@RequestMapping("/delete")
	public @ResponseBody MessageJson delete(@RequestParam("ids") Long[] ids){
		if(ids == null || ids.length == 0){
			throw new ValidationException("没有删除");
		}
		for(Long id : ids){
			menuService.removeById(id);
		}
		return MessageJson.information("成功删除"+ids.length+"条");
	}

	/**
	 * menu菜单的数据校验
	 * @param menu
	 * @param message
	 * @return
	 */
	private boolean validate( Menu menu,StringBuffer message){


		if(null == menu){
			throw new ValidationException("用户不存在");
		}
		if(null == menu.getTitle() || menu.getTitle().equals("")){
			throw new ValidationException("名称不能为空");
		}else{
			/*if(!menuService.isPropertyUnique("title",  menu.getTitle(),  menu.getId())){
				throw new ValidationException("名称已经存在,重新填写");
			}*/
			return true;

		}
	}


	/**
	 * 通过权限code得到相对应的title
	 * @param code
	 * @return
	 */
	private String getPrivilegeTitle(String code){
		Privilege p = PrivilegeService.getPrivilege(code);
		if(null == p)
			return "";
		else
			return p.getTitle();
	}

	/**
	 * 通过权限code得到相应的URL
	 * @param code
	 * @return
	 */
	private String getPrivilegeURL(String code){
		Privilege p = PrivilegeService.getPrivilege(code);
		if(null == p)
			return "";
		else
			return p.getUrl();
	}
}
